/* Octopus PDF - A simple document viewer for Android.
   Copyright (C) 2013  Gerald Thaler

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */
package de.geraldthaler.octopuspdf;

import static de.geraldthaler.octopuspdf.control.DocControl.PAGE_MODE_ONE_PAGE;
import static de.geraldthaler.octopuspdf.control.DocControl.PAGE_MODE_TWO_PAGES_WITHOUT_TITLE;
import static de.geraldthaler.octopuspdf.control.DocControl.PAGE_MODE_TWO_PAGES_WITH_TITLE;

import java.io.File;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import de.geraldthaler.octopuspdf.docrender.DocSource;
import de.geraldthaler.octopuspdf.view.MainView;
import de.geraldthaler.octopuspdf.view.PageModeEvent;
import de.geraldthaler.octopuspdf.view.PageNrEvent;
import de.geraldthaler.octopuspdf.view.PasswordEvent;

/**
 * @author Gerald Thaler
 */
public final class MainActivity extends Activity {
    private static String getFile(final Intent intent) {
		final Uri data = intent.getData();
		if (data != null)
			return Uri.decode(data.getEncodedPath());
    	return intent.getStringExtra("file");
    }

	private static int getDocType(final String file) {
		final String fileLower = file.toLowerCase(Locale.getDefault());
		if (fileLower.endsWith(".cbz"))
			return DocSource.DOC_TYPE_CBZ;
		if (fileLower.endsWith(".xps") || fileLower.endsWith(".rels"))
			return DocSource.DOC_TYPE_XPS;
		return DocSource.DOC_TYPE_PDF;
	}

    private MainView view;
	private String havePassword;
	private boolean passwordUsed;
	private RelativeLayout controls;
	private boolean controlsVisible;
	private int motionCount;
	private SeekBar pageBar;
	private TextView pageNrText;
	private FrameLayout frameLayout;
	private int pageCount = 100;
	private int pageMode;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        System.gc();
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        final Bundle state;
        if (savedInstanceState == null) {
            state = null;
            havePassword = null;
            pageMode = PAGE_MODE_ONE_PAGE;
        } else {
            state = savedInstanceState.getParcelable("de.geraldthaler.octopuspdf");
            havePassword = state.getString("password");
            pageMode = state.getInt("pageMode");
        }
        passwordUsed = false;
        final Intent intent = getIntent();
        String file = getFile(intent);
        final String intentPassword = intent.getStringExtra("password");
        if (intentPassword != null)
        	havePassword = intentPassword;
        final int intentPageMode = intent.getIntExtra("pageMode", -1);
        if (intentPageMode >= 0)
        	pageMode = intentPageMode;
        final DocSource docSource = new DocSource(new File(file), getDocType(file));
        frameLayout = new FrameLayout(this);
        view = new MainView(this, state, docSource, pageMode);
        frameLayout.addView(view);
        controls = (RelativeLayout) getLayoutInflater().inflate(R.layout.controls, null);
        pageBar = (SeekBar) controls.findViewById(R.id.pageSlider);
        pageBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(final SeekBar seekBar) {
				view.sendEvent(new PageNrEvent(seekBar.getProgress()));
			}

			@Override
			public void onStartTrackingTouch(final SeekBar seekBar) {
				// nothing
			}

			@Override
			public void onProgressChanged(final SeekBar seekBar, int progress, boolean fromUser) {
				setPageNrText(progress);
			}
		});
        pageNrText = (TextView) controls.findViewById(R.id.pageNr);
        final ImageButton settingsButton = (ImageButton) controls.findViewById(R.id.settingsButton);
        settingsButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(final View v) {
				onSettings();
			}
		});
        controlsVisible = true;
		frameLayout.addView(controls);
        setContentView(frameLayout);
        motionCount = 0;
    }

	public void onMotion() {
		if (motionCount == 0) {
			if (controlsVisible) {
				frameLayout.removeView(controls);
				controlsVisible = false;
			}
			motionCount = 10;
		} else
			--motionCount;
	}

	public void requestPassword() {
		if (!passwordUsed && havePassword != null) {
			view.sendEvent(new PasswordEvent(havePassword));
			passwordUsed = true;
			return;
		}
		final EditText passwordView = new EditText(this);
		passwordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
		passwordView.setTransformationMethod(new PasswordTransformationMethod());

		final AlertDialog alert = new AlertDialog.Builder(this).create();
		alert.setTitle(R.string.enter_password);
		alert.setView(passwordView);
		alert.setButton(AlertDialog.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(final DialogInterface dialog, final int which) {
				havePassword = passwordView.getText().toString();
				view.sendEvent(new PasswordEvent(havePassword));
			}
		});
		alert.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		});
		alert.show();
	}

	public void onTap() {
		if (controlsVisible)
			frameLayout.removeView(controls);
		else 
			frameLayout.addView(controls);
		controlsVisible = !controlsVisible;
		motionCount = 10;
	}

	public void setPageNr(final int pageNr, final int pageCount) {
		pageBar.setMax(pageCount - 1);
		pageBar.setProgress(pageNr);
		this.pageCount = pageCount;
		setPageNrText(pageNr);
	}

	@Override
    protected void onDestroy() {
        super.onDestroy();
        view.dispose();
        view = null;
        System.gc();
    }

    @Override
    protected void onPause() {
        view.onPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        view.onResume();
    }

    @Override
    protected void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        final Bundle state = new Bundle();
        state.putString("password", havePassword);
        state.putInt("pageMode", pageMode);
        view.saveInstanceState(state);
        outState.putParcelable("de.geraldthaler.octopuspdf", state);
    }

	void onSettings() {
		final View dialog = getLayoutInflater().inflate(R.layout.settings, null);
		final AlertDialog alert = new AlertDialog.Builder(this).create();
		alert.setView(dialog);
		final RadioButton buttonOnePage = (RadioButton) dialog.findViewById(R.id.pageModeOne);
		final RadioButton buttonTwoWith = (RadioButton) dialog.findViewById(R.id.pageModeTwoWith);
		final RadioButton buttonTwoWithout = (RadioButton) dialog.findViewById(R.id.pageModeTwoWithout);
		alert.setButton(AlertDialog.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(final DialogInterface dialog, final int which) {
				if (buttonOnePage.isChecked())
					pageMode = PAGE_MODE_ONE_PAGE;
				else if (buttonTwoWith.isChecked())
					pageMode = PAGE_MODE_TWO_PAGES_WITH_TITLE;
				else if (buttonTwoWithout.isChecked())
					pageMode = PAGE_MODE_TWO_PAGES_WITHOUT_TITLE;
				view.sendEvent(new PageModeEvent(pageMode));
			}
		});
		switch (pageMode) {
		case PAGE_MODE_ONE_PAGE:
			buttonOnePage.setChecked(true);
			break;
		case PAGE_MODE_TWO_PAGES_WITH_TITLE:
			buttonTwoWith.setChecked(true);
			break;
		default:
			buttonTwoWithout.setChecked(true);
		}
		alert.show();
	}

	private void setPageNrText(final int pageNr) {
		pageNrText.setText(" " + (pageNr + 1) + " / " + pageCount + ' ');
	}
}
